<template>
	<view class="scratcher_table">
		<view class="scratcher_table_con bg_style" :style="{backgroundImage:'url('+imgUrl+'scra_bg_s.png)'}">
			<view class="scratcher_center">
				<canvas canvas-id="myCanvas" disable-scroll @touchstart="onTouchStartDraw" @touchmove="onTouchMove"
					@touchend="onTouchEnd" id="myCanvas" class="scratch_canvas" style="width: 100%;height: 280rpx;"
					v-if="canvasShow" />
					
					
				<view v-else :style="{height:(height-16)+'px',width:width+'px',backgroundImage:'url(/static/common/scra_bg_cs.png)'}" class="scratch_canvas_img">
					
				</view>
				<!-- <image src="/static/common/scra_bg_cs.png" mode="aspectFit" v-else class="scratch_canvas_img"></image> -->
				<view class="scratcher_res flex_row_center_center">
					<view class="">
						<text>{{canvasShow?lotResult.prizeName:''}}</text>
					</view>
				</view>
				<view class="scratcher_res_res flex_column_center_center "
					v-if="reactgetAcDetail.acState.flag==0||reactgetAcDetail.acState.flag==2">
					<view class="flex_column_center_center bg_style"
						:style="{backgroundImage:'url('+imgUrl+'scra_bg_c.png)',height:'100%',width:'84%'}">
						<view class="res_desc">{{reactgetAcDetail.acState.desc}}</view>
						<view class="res_sub">{{reactgetAcDetail.acState.time}}</view>
					</view>
				</view>
				
				
				
				
				
				
				
				
				
			</view>
		</view>
		
		
		
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgUrl: getApp().globalData.imgUrl + 'lottery/',
				current: 0,
				ctx: null,
				points: [],
				originData: [],
				height: 120,
				width: 274,
				lotResult: {},
				startS: true,
				backHeight: 0,
				scratchCom: false,
				canvasShow: true,
				isCreated: false
			}
		},
		inject: ['getAcDetail', 'relotDetail'],
		props: ['userInt', 'drawId'],
		computed: {
			reactgetAcDetail() {
				return this.isCreated ? this.getAcDetail() : {}
			},
			getlotDetail() {
				return this.isCreated ? this.relotDetail() : {}
			},
		},
		created() {
			this.isCreated = true


			uni.$on('openShare', (e) => {

				this.canvasShow = !e

				if (e) {
					this.$nextTick(() => {
						this.initDrawCanvas()
					})
				}
			})
		},
		mounted() {
			this.initDrawCanvas()
		},
		methods: {

			initDrawCanvas() {

				if (this.reactgetAcDetail.acState.flag != 1) {
					return
				}
				this.scratchCom = false
				let clientWidth = uni.getSystemInfoSync().windowWidth
				//针对不同机型的位置，和宽高比例换算---start
				let pos = parseInt(clientWidth * (30 / 414))
				this.height = parseInt(clientWidth * (140 / 414))
				this.width = parseInt(clientWidth * (284 / 414))
				//针对不同机型的位置，和宽高比例换算---end
				this.ctx = uni.createCanvasContext('myCanvas', this.$scope)
				let _this = this
				this.ctx.drawImage(`/static/common/scra_bg_cs.png`, pos, pos, this.width, this.height)
				this.ctx.draw(true)

			},

			onTouchStartDraw(e) {
				if (this.userInt.remainNum == 0) {
					this.$api.msg(this.$L('您的抽奖次数已用完'))
					return
				} else if (this.userInt.integral < this.getlotDetail.integralUse) {
					this.$api.msg(this.$L('您的抽奖积分不足'))
					return
				}


				//这是针对，间断性刮刮动作的处理，防止间断性动作触发多次抽奖
				if (!this.startS) {
					this.onTouchStart(e)
					return
				}

				//防止刮完出结果后瞬间，刮动再次出发抽奖
				if (this.scratchCom) {
					return
				}



				this.$request({
					url: 'v3/promotion/front/draw/doDraw',
					method: 'POST',
					data: {
						drawId: this.drawId,
					}
				}).then(res => {
					if (res.state == 200) {
						this.lotResult = res.data
						this.startS = false
						this.onTouchStart(e)
					} else {
						this.$api.msg(res.msg)
					}
				})
			},

			onTouchStart(e) {


				if (this.userInt.remainNum == 0 || this.userInt.integral < this.getlotDetail.integralUse) {
					return
				}

				let {
					x,
					y
				} = e.changedTouches[0]
				this.points.push([x, y])
				this.originData.push([
					[x, y]
				])
			},
			onTouchMove(e) {

				if (this.userInt.remainNum == 0 || this.userInt.integral < this.getlotDetail.integralUse) {
					return
				}

				const {
					x,
					y
				} = e.changedTouches[0]
				this.points.push([x, y])
				this.originData[this.originData.length - 1] && this.originData[this.originData.length - 1].push([x, y])
				this.draw()
			},
			onTouchEnd() {

				if (this.userInt.remainNum == 0 || this.userInt.integral < this.getlotDetail.integralUse) {
					return
				}

				this.points = []
				this.$nextTick(() => {
					this.getFilledPercentage().then((data) => {
						if (parseInt(data) >= 65) { //刮的区域大于等于设定的值就清除canvas
							if (!this.scratchCom) {
								this.ctx.clearRect(0, 0, this.width, this.height);
								this.startS = true
								this.scratchCom = true
								this.ctx.draw();
								this.$emit('res', 'complete', this.lotResult)
							}

						}
					})
				})

			},
			
			
			show(){
				this.canvasShow = !this.canvasShow
				
				if (this.canvasShow) {
					this.$nextTick(() => {
						this.initDrawCanvas()
					})
				}
			},
			
			
			
			
			draw() {
				const {
					ctx,
					points
				} = this
				if (points.length < 2) return
				ctx.moveTo(...points.shift())
				ctx.lineTo(...points[0])
				this.ctx.clearRect(...points[0], 20, 20);
				ctx.draw(true)
			},
			//计算清除的百分占比
			getFilledPercentage() {
				const fillePercent = new Promise((resolve) => {
					uni.canvasGetImageData({
						canvasId: 'myCanvas',
						x: 30,
						y: 30,
						width: this.width,
						height: this.height,
						success: (res) => {
							// res.data是个数组，存储着指定区域每个像素点的信息，数组中4个元素表示一个像素点的rgba值
							let pixels = res.data;
							let transPixels = [];
							for (let i = 0; i < pixels.length; i += 4) {
								// 严格上来说，判断像素点是否透明需要判断该像素点的a值是否等于0，
								// 为了提高计算效率，这儿设置当a值小于128，也就是半透明状态时就可以了
								if (pixels[i + 3] < 128) {
									transPixels.push(pixels[i + 3]);
								}
							}
							resolve((transPixels.length / (pixels.length / 4) * 100).toFixed(2))
						},
					}, this.$scope)
				})
				return fillePercent
			},
			change(e) {
				this.current = e.detail.current + 1
			},
			open() {
				this.$refs.popInfo.open()
			},

		}
	}
</script>

<style lang="scss">
	.bg_style {
		background-position: center center;
		background-repeat: no-repeat;
		background-size: contain;
	}

	.scratcher_table {
		margin-top: 10rpx;
		padding: 0 60rpx;

		.scratcher_table_con {
			height: 335rpx;
			margin: 40rpx 0;
			position: relative;

			.scratcher_center {
				position: relative;
				padding: 2rpx;
			}

			.scratch_canvas_img {
				display: block;
				width: 514rpx;
				height: 228rpx;
				margin: 0 auto;
				margin-top: 30px;
				background-repeat: no-repeat;
				background-size: cover;
				background-position: 0 0;
			}

			.scratcher_res {
				width: 100%;

				font-weight: 600;
				position: absolute;
				top: 0;
				z-index: 0;

				view {
					width: 514rpx;
					height: 300rpx;
					text-align: center;
					line-height: 300rpx;

					text:first-child {
						color: #FC1D1C;
						font-size: 70rpx;
					}

					text:last-child {
						color: #FB720D;
						font-size: 40rpx;
					}
				}
			}

			.scratcher_res_res {
				width: 100%;
				font-size: 33rpx;
				font-weight: 600;
				position: absolute;
				top: 0;
				z-index: 99;
				height: 320rpx;

				.res_desc {
					min-width: 170rpx;
					padding: 0 6rpx;
					height: 50rpx;
					background: #BBBBBB;
					border-radius: 3px;
					text-align: center;
					line-height: 50rpx;
					font-family: AliHYAiHei;
					color: #fff;
				}

				.res_sub {
					margin-top: 26rpx;
					font-size: 26rpx;
					font-family: SourceHanSansCN;
					font-weight: 600;
					color: #333333;
				}
			}

			.scratch_canvas {
				position: absolute;
				z-index: 99;
			}

			.scratcher_times {
				font-size: 28rpx;
				font-family: SourceHanSansCN;
				font-weight: bold;
				color: #BF4001;
				text-align: center;
				height: 70rpx;
				line-height: 70rpx;
			}

			.scratcher_desc {
				position: absolute;
				bottom: 30rpx;
				font-size: 22rpx;
				font-family: SourceHanSansCN;
				color: #BF4001;
				text-align: center;
				height: 50rpx;
				line-height: 50rpx;
			}
		}
	}
</style>
